package com.yf.screenshot

import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.wink_172.library.activity.SmartActivity
import com.yangfan.screenshot.log.LogUtil
import com.yangfan.screenshot.viewmodel.AppViewModel
import org.xutils.x

/**
 * @author : yangfan
 * @date : 2022/12/13-16:13
 * desc   : 长图预览界面
 */
class PreviewActivity : SmartActivity() {
    private val TAG = PreviewActivity::class.java.simpleName
    private var imageView: SubsamplingScaleImageView? = null
    private var mProgressBar: ProgressBar? = null
    private var mAppViewModel: AppViewModel? = null

    /**
     * 图片地址
     */
    private var bitmap: Bitmap? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_preview)
        val textView = findViewById<TextView>(R.id.tvVersion)
        textView.text = "版本：" + BuildConfig.VERSION_NAME
        if (applicationContext is App) {
            mAppViewModel = ViewModelProvider((applicationContext as App)).get(
                AppViewModel::class.java
            )
        }
        imageView = findViewById<View>(R.id.imageView) as SubsamplingScaleImageView
        mProgressBar = findViewById(R.id.progressBar)


        findViewById<View>(R.id.confirm).setOnClickListener {
            finish()
        }
        updateBitmap()
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        LogUtil.d(TAG, "onNewIntent====")
        val progress = intent.getIntExtra("progress", 0)
        val total = intent.getIntExtra("total", 0)
        LogUtil.d(TAG, "progress = $progress;total = $total")
        if (total > 0) {
            mProgressBar!!.visibility = View.VISIBLE
            mProgressBar!!.max = total
            mProgressBar!!.progress = progress
            imageView!!.visibility = View.GONE
        } else {
            updateBitmap()
        }
    }

    fun updateBitmap(){
        bitmap = mAppViewModel!!.bitmapLiveData.value
        LogUtil.d(TAG, "PreviewActivity bitmap = $bitmap")
        if (bitmap != null) {
            imageView!!.visibility = View.VISIBLE
            mProgressBar!!.visibility = View.GONE
            imageView!!.setImage(ImageSource.bitmap(bitmap!!))
            saveImage(bitmap!!)
        }
    }

    private fun saveImage(bitmap: Bitmap) {
        try {
            //获取要保存的图片的位图
            //创建一个保存的Uri
            val saveUri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                ContentValues()
            )
            if (TextUtils.isEmpty(saveUri.toString())) {
                Log.e(TAG, "saveImage: ====>>01")
                return
            }
            val outputStream = contentResolver.openOutputStream(saveUri!!)
            //将位图写出到指定的位置
            //第一个参数：格式JPEG 是可以压缩的一个格式 PNG 是一个无损的格式
            //第二个参数：保留原图像90%的品质，压缩10% 这里压缩的是存储大小
            //第三个参数：具体的输出流
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
                Log.e(TAG, "saveImage: ====>>02" + saveUri.path + saveUri.toString())
                AlbumNotifyHelper.insertImageToMediaStore(
                    x.app(),
                    saveUri.path,
                    System.currentTimeMillis()
                )
                Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show()
            } else {
                Log.e(TAG, "saveImage: ====>>03")
                Toast.makeText(this, "保存失败！", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (bitmap != null) {
            bitmap!!.recycle()
        }
        if (mAppViewModel != null) {
            mAppViewModel!!.bitmapLiveData.value = null
        }
    }
}